<!--
 * @Author: njz
 * @FileDescription: 价格走势
-->
<template>
  <com-box :title="lineState.title">
    <template #titleRight>
      <slot name="titleRight" />
    </template>
    <template v-slot>
      <div class="box">
        <div class="jgdb-msg" v-show="lineState.ifShow">
          此商品无（{{ menuName }}）数据
        </div>
        <charts :params="lineState.params" v-show="!lineState.ifShow"></charts>
      </div>
      <div class="box-bar echart-item">
        <div class="jgdb-msg" v-show="BarState.ifShow">
          此商品无（进销存）量数据
        </div>
        <charts class="line-chart" :params="BarState.params"></charts>
      </div>
    </template>
  </com-box>
</template>
<script lang="ts">
import { defineComponent, reactive, watch } from 'vue'
import * as echarts from 'echarts'
import httpRequest from '@/service'
import comBox from '@/components/comBox/comBox.vue'
interface IState {
  title?: string
  isGroup: boolean
  ifShow?: boolean
  itemColor?: any
  params: any
  getData: (goodsId: string, adcode?: string) => void
}
export default defineComponent({
  name: 'jgzs',
  components: {
    comBox
  },
  props: {
    goodsId: {
      type: String,
      default: ''
    },
    isJszsBar: {
      type: Boolean,
      default: false
    },
    adCodes: {
      type: String,
      default: ''
    },
    adname: {
      type: String,
      default: ''
    },
    menuName: {
      type: String,
      default: ''
    },
    menuId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    // 折线图
    const lineState: IState = reactive({
      title: '',
      ifShow: false,
      isGroup: false,
      forceRedraw: true, // 强制重绘
      params: {
        loading: true,
        // height: '245px',
        height: '265px',
        map: {
          value: '价格'
        },
        options: {
          dataset: {
            dimensions: ['name', 'value'],
            source: []
          },
          legend: {
            show: false
          },
          xAxis: [
            {
              axisLabel: {
                show: true,
                rotate: 35,
                fontSize: '13px'
              }
            }
          ],
          yAxis: [
            {
              name: ''
            }
          ],
          grid: {
            top: 43,
            bottom: 8
          },
          dataZoom: [
            {
              show: false,
              type: 'slider',
              start: 0,
              end: 100
            }
          ],
          series: [
            {
              type: 'line',
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: {
                color: '#00c6ff',
                borderColor: 'rgba(0,198,255,0.5)',
                borderWidth: 5
              },
              connectNulls: true,
              label: {
                show: false
              },
              emphasis: {
                label: {
                  show: true,
                  position: 'top',
                  fontSize: '16px'
                }
              },
              smooth: true,
              markPoint: {
                symbol: 'pin',
                symbolSize: 1,
                label: {
                  show: true,
                  position: 'top',
                  color: '#00baff',
                  distance: 12,
                  fontWeight: 'bold',
                  fontFamily: 'AliHYAiHei',
                  fontSize: '16px'
                },
                data: [
                  {
                    type: 'max'
                  },
                  {
                    type: 'min'
                  }
                ]
              },
              areaStyle: {
                color: [[['#072770', '#166BE9']]]
              }
            }
          ]
        },
        event: {
          customEvent: (chartInstance: echarts.ECharts) => {
            chartInstance.group = 'group1'
            lineState.isGroup = true
          }
        }
      },
      getData: (goodsId, adcode) => {
        lineState.params.loading = true
        lineState.params.options.series[0].markPoint.data = []
        httpRequest
          .get({
            url: 'M2P1JgzsLine',
            params: {
              goodsId,
              adcode,
              menuId: props.menuId ? props.menuId : 'retailPrice'
            }
          })
          .then((res) => {
            if (res.code === 200 && res.data.length > 0) {
              handDataFormat(res.data)
              lineState.title = res.title + '(' + props.menuName + ')'
              lineState.params.options.series[0].markPoint.data = [
                {
                  type: 'max'
                },
                {
                  type: 'min'
                },
                {
                  name: '当前值',
                  value: res.data[res.data.length - 1].value,
                  xAxis: res.data[res.data.length - 1].name,
                  yAxis: res.data[res.data.length - 1].value
                }
              ]
              lineState.params.options.yAxis[0].name = res.unit + '\n'
              // res.data.forEach((item: any, index: number) => {
              //   if (index == 1 || index == res.data.length - 1) {
              //     item.value = 0
              //   }
              //   const bool = parseFloat(item.value)
              //   if (isNaN(bool) || bool == 0) {
              //     item.value = ''
              //   }
              // })
              lineState.params.options.dataset.source = res.data
              // isShowDataZoom(res.data.length, lineState.params.options)
              lineState.params.loading = false
              lineState.ifShow = false
            } else {
              lineState.params.loading = false
              lineState.ifShow = true
            }
          })
          .catch(() => {
            console.log('请求失败')
          })
      }
    })

    //柱状图
    const BarState: any = reactive({
      isGroup: false,
      ifShow: false,
      params: {
        loading: true,
        forceRedraw: true, // 强制重绘
        // height: '210px',
        map: {},
        options: {
          dataset: {
            dimensions: [],
            source: []
          },
          title: {
            show: true,
            text: '',
            left: '10px',
            top: '1%',
            textStyle: {
              fontSize: '16px',
              fontFamily: 'Microsoft YaHei',
              color: 'rgba(162, 199, 255,1)'
            }
          },
          legend: {
            show: true,
            right: 0,
            top: 8,
            itemWidth: 15,
            width: '70%'
          },
          // 待完善：此处如果注释会导致添加不上axisLabel->fontSize的chartFontSize，因为递归合并时直接赋值xAxis全局配置了
          xAxis: [
            {
              fontSize: '13px'
              // axisLabel: {
              //   formatter: function (value: string) {
              //     const srt = value.split('-')
              //     return srt[1] + '-' + srt[2]
              //   }
              // }
            }
          ],
          yAxis: [
            {
              fontSize: '13px',
              splitLine: {
                show: false
              },
              name: ['']
            }
          ],
          grid: {
            top: 60,
            // bottom: 49,
            bottom: '40px',
            // top: 42,
            // bottom: 35,
            left: 10,
            right: 0
          },
          dataZoom: [
            {
              show: true,
              type: 'slider',
              start: 0,
              end: 100,
              width: '80%',
              left: '10%',
              bottom: 22,
              height: 15,
              borderColor: '#166beb',
              handleStyle: {
                color: '#166beb',
                borderColor: '#166beb',
                borderWidth: 4
              },
              moveHandleSize: 10,
              moveHandleStyle: {
                color: '#166beb'
              },
              textStyle: {
                color: '#00c6ff'
              },
              emphasis: {
                handleStyle: {
                  color: '#00c6ff',
                  borderColor: '#00c6ff',
                  borderWidth: 4
                },
                moveHandleStyle: {
                  color: '#00c6ff'
                }
              }
            }
          ],
          series: [
            {
              type: ['bar', 'bar', 'bar'],
              label: {
                show: false
              },
              itemStyle: {
                // color: ['#0CA2D9', '#ea68a2', '#1da7ff', '#ec6941', '#ffba0a']
                color: [[['#40c4ff', '#0d66ff'], 'right']]
              },
              areaStyle: {
                opacity: 0
              }
            }
          ]
        },
        event: {
          customEvent: (chartInstance: echarts.ECharts) => {
            chartInstance.group = 'group1'
            BarState.isGroup = true
          }
        }
      },
      getData: (goodsId: any) => {
        BarState.params.loading = true
        httpRequest
          .get({
            url: 'M2P1JgzsPriceBar',
            params: {
              goodsId,
              menuId: props.menuId ? props.menuId : 'retailPrice'
            }
          })
          .then((res) => {
            if (res.code === 200 && Object.keys(res.map).length > 0) {
              BarState.params.options.dataset.dimensions = [
                'name',
                ...Object.keys(res.map)
              ]
              BarState.params.options.dataset.source = res.data
              BarState.params.options.yAxis[0].name = [res.unit]
              BarState.params.options.title.text = res.title
              BarState.params.map = res.map
              echarts.connect('group1')
              setTimeout(() => {
                BarState.params.loading = false
                BarState.ifShow = false
              })
            } else {
              BarState.params.loading = false
              BarState.ifShow = true
            }
          })
          .catch(() => {
            console.log('请求失败')
          })
      }
    })
    // 是否显示下方滑块
    const isShowDataZoom = (long = 0, options: any) => {
      if (long < 17) {
        options.dataZoom[0].show = false
        options.dataZoom[0].start = 0
        options.grid.bottom = 5
      } else {
        options.dataZoom[0].show = false
        options.dataZoom[0].start = 50
        options.grid.bottom = 5
      }
    }

    // 折线图(猪粮比)
    const LineZLBState: IState = reactive({
      isGroup: false,
      itemColor: [
        {
          color: '#F19802',
          borderColor: 'rgba(243,152,3,.3)'
        },
        {
          color: '#00FEFD',
          borderColor: 'rgba(254,255,0,.3)'
        }
      ],
      params: {
        loading: true,
        // height: '210px',
        height: '245px',
        map: {},
        options: {
          dataset: {
            dimensions: [],
            source: []
          },
          legend: {
            show: true,
            right: 10
          },
          xAxis: [
            {
              show: false
            }
          ],
          yAxis: [
            {
              name: ['元/50公斤'],
              position: ['left', 'right'],
              max: ['300', '1900']
            }
          ],
          grid: {
            top: '5%',
            bottom: '20px'
          },
          series: [
            {
              type: ['line', 'line'],
              // itemStyle: {
              //   color: [],
              //   borderColor: []
              // },
              itemStyle: [],
              label: {
                show: false
              },
              connectNulls: true,
              smooth: true,
              areaStyle: {
                opacity: 0
              },
              symbolSize: 8,
              symbol: 'circle',
              yAxisIndex: [0, 1, 0]
            }
          ],
          dataZoom: [
            // {
            //   show: false,
            //   type: 'slider',
            //   start: 50,
            //   end: 100
            // }
            {
              show: false,
              type: 'slider',
              start: 50,
              end: 100,
              width: '100%',
              height: 15,
              borderColor: '#166beb',
              handleStyle: {
                color: '#166beb',
                borderColor: '#166beb',
                borderWidth: 4
              },
              moveHandleSize: 10,
              moveHandleStyle: {
                color: '#166beb'
              },
              textStyle: {
                color: '#00c6ff'
              },
              emphasis: {
                handleStyle: {
                  color: '#00c6ff',
                  borderColor: '#00c6ff',
                  borderWidth: 4
                },
                moveHandleStyle: {
                  color: '#00c6ff'
                }
              }
            }
          ]
        },
        event: {
          customEvent: (chartInstance: echarts.ECharts) => {
            chartInstance.group = 'group1'
            LineZLBState.isGroup = true
          }
        }
      },
      getData: (goodsId, adcode) => {
        LineZLBState.params.loading = true
        httpRequest
          .get({ url: 'M2P1JgzsZlbLine', params: { goodsId, adcode } })
          .then((res) => {
            if (res.code === 200) {
              LineZLBState.params.map = res.map
              LineZLBState.params.options.dataset.dimensions = [
                'name',
                ...Object.keys(res.map)
              ]
              let arrLegend: any = []
              let arrSeries: any = []
              Object.values(res.map).forEach((item, index) => {
                arrLegend.push({
                  name: item,
                  textStyle: {
                    color: LineZLBState.itemColor[index].color
                  }
                })
                arrSeries.push({
                  color: LineZLBState.itemColor[index].color,
                  borderColor: LineZLBState.itemColor[index].borderColor,
                  borderWidth: 4
                })
              })
              let val1 = 0
              res.data.forEach((item: any) => {
                val1 = val1 > Number(item.value1) ? val1 : Number(item.value1)
              })

              isShowDataZoom(res.data.length, LineZLBState.params.options)

              LineZLBState.params.options.yAxis[0].max = [300, val1 + 200]
              LineZLBState.params.options.yAxis[0].name = [res.unit]
              LineZLBState.params.options.legend.data = arrLegend
              LineZLBState.params.options.series[0].itemStyle = arrSeries
              LineZLBState.params.options.dataset.source = res.data
              LineZLBState.params.loading = false
            }
          })
          .catch(() => {
            console.log('请求失败')
          })
      }
    })
    const handDataFormat = (arr: any) => {
      arr.forEach((item: any) => {
        if (item.value && item.value !== '') {
          item.value = parseFloat(item.value)
        }
      })
    }
    const refreshData = () => {
      BarState.getData(props.goodsId)
    }
    watch(
      () => LineZLBState.isGroup,
      (lineGroup) => {
        if (lineGroup) {
          // 图表实例实现联动
          echarts.connect('group1')
        }
      }
    )
    watch(
      () => [props.goodsId, props.adCodes],
      ([goodVal, adVal], [val2, val3]) => {
        if (!adVal) {
          return
        }
        // if (props.menuName == '批发价格' && goodVal == val2) {
        //   return
        // }
        if (!props.isJszsBar) {
          BarState.getData(goodVal)
          lineState.getData(goodVal, adVal)
        } else {
          const arr = goodVal.split(',')
          // LineZLBState.getData(`${arr[1]},${arr[2]}`, adVal)
          lineState.getData(arr[0], adVal)
        }
      }
    )
    watch(
      () => props.menuName,
      (menuName) => {
        if (menuName) {
          lineState.title = '价格走势(' + menuName + ')'
          BarState.getData(props.goodsId)
          lineState.getData(props.goodsId, props.adCodes)
        }
      }
    )
    return {
      lineState,
      LineZLBState,
      BarState,
      refreshData
    }
  }
})
</script>
<style lang="less" scoped>
.box-bar {
  border-top: 2px solid #1b3a80;
  // height: calc(50% + 20px);
  height: 50%;
}
.box {
  // height: calc(50% - 20px);
  height: 50%;
}
.jgdb-msg {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 31px;
  font-weight: bold;
  color: #ef7809;
}
</style>
